package com.ts.manager;

import android.content.Intent;
import android.os.Process;

import com.easemob.chat.CmdMessageBody;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMMessage;
import com.rio.core.L;
import com.rio.core.U;
import com.rio.helper.Sleeper;
import com.rio.layout.LayoutManager;
import com.rio.layout.TaskManager;
import com.rio.layout.view.SimpleTask;
import com.ts.host.APP;

public class ConntectManager {

	private static final int WAITING_TIME = 10 * 1000;//
	
	private static final int HEARTE_TIME = 6 * 20;// 6 = 一分钟 
	
	private static int mBeatHeart;
	
	private static boolean mConnected;
	
	private static boolean mStart;
	
	private static SimpleTask mTask;
	
	private static SimpleTask getTask(){
		if(U.isNull(mTask)){
			mTask = new SimpleTask() {
	
				@Override
				public Object onBGThread(Object... params) throws Exception {
					Sleeper.sleep(WAITING_TIME);
					mBeatHeart++;
					if(mBeatHeart > HEARTE_TIME){
						mBeatHeart = 0;
						sendBeate();
					}else{
						getActon();
					}
					postDelay();
					return super.onBGThread(params);
				}
				



				@Override
				public void onUIThread(Object data, Object... params)
						throws Exception {
					super.onUIThread(data, params);
				}
			};
		}
		return mTask;
		
	}
	

	
	public static void setConnected(boolean connected) {
		mConnected = connected;
	}

	public static void start(){
		mConnected = true;
		mStart = true;
		postDelay();
	}
	
	public static void destory(){
		mStart = false;
		mTask = null;
	}


	private static void postDelay() {
		if(mStart)TaskManager.getInstance().async(getTask());
	}

	private static void sendBeate() {
		mConnected = false;
		if(MachineManager.getInstance().isConnected() && U.notNull(MachineManager.getInstance().getMachine().HXusername)){				
				L.i("test connection");
				EMMessage message = EMMessage.createSendMessage(EMMessage.Type.CMD);
			 	String action = APP.TEST;
			 	CmdMessageBody cmdBody = new CmdMessageBody(action);
			 	message.setReceipt(MachineManager.getInstance().getMachine().HXusername);
			 	message.addBody(cmdBody);
			 	EMChatManager.getInstance().sendMessage(message, null);
			}		
	}

	private static void getActon() {
		if(mConnected){
			L.i("message fine");
		}else if(mStart){
			L.i("message time out");
			Intent i = new Intent(APP.ACTION);
			i.putExtra(APP.ACTION, Process.myPid());
			LayoutManager.getInstance().getActivity().startService(i);
			LayoutManager.getInstance().finish();
		}
		
	}
}
